package com.zhu.androidsample.common;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.zhu.androidsample.common.i.IMessage;

/**
 * Created by ZCP on 2015/11/17.
 * mail:43426073@qq.com
 */
public abstract class BaseActivity extends Activity implements Handler.Callback, IMessage {
    public static final String TAG = "DEBUG";
    public static final int START_LOADING = 0x0001;
    public static final int END_LOADING = 0x0002;
    final Handler handler = new Handler(this);
    Dialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    /**
     * Handler.Callback
     * handler向子类提供handler的get方法
     *
     * @return 获取activity的handler
     */
    protected Handler getHandler() {
        return handler;
    }

    /**
     * IMessage
     * 获得消息的方法
     *
     * @param what 消息种类，由activity中确定的静态常量担当
     * @return 返回消息池里的一个消息
     */
    @Override
    public Message getMessage(int what) {
        return handler.obtainMessage(what);
    }

    /**
     * IMessage
     * 获得消息的方法
     *
     * @param what 消息种类，由activity中确定的静态常量担当
     * @param obj  消息内容。随意你喜欢放任何东西
     * @return 返回消息池里的一个消息
     */
    @Override
    public Message getMessage(int what, Object obj) {
        return handler.obtainMessage(what, obj);
    }

    /**
     * 接收到消息的回调方法
     *
     * @param msg 通知消息
     * @return 返回消息处理结果
     */
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case START_LOADING:
                startLoading();
                break;
            case END_LOADING:
                endLoading();
                break;
            default:
                Log.d(TAG, "handleMessage() called with: " + "msg = [" + msg + "]");
                break;
        }
        return true;
    }

    /**
     * 业务逻辑
     */
    protected Dialog getProgressDialog() {

        return null;
    }

    private void startLoading() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.show();
    }

    private void endLoading() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.dismiss();

    }

}
